<template>
  <upload-excel :on-success="onSuccess" />
</template>

<script>
import { importEmployee } from '@/api/employees.js'
export default {
  methods: {
    onSuccess({ results }) {
      // console.log(data)
      // 拿到当前路由实例配置的query参数
      const { type } = this.$route.query
      this[type](results)
    },
    // 抽离员工导入逻辑
    // 每次在不同的页面复用导入逻辑时,要保证函数名与type参数名相同,就可以不用通过if else判断再处理逻辑直接使用中括号取值语法调用方法
    async user(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const obj = {}
      const arr = []
      results.forEach((item) => {
        // console.log(item, '=====item====')
        Object.keys(item).forEach((key) => {
          if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
            obj[userRelations[key]] = this.formatDate(item[key], '-')
            return
          }
          obj[userRelations[key]] = item[key]
          // console.log(userRelations[key], '====userRelations[key]====')
          // console.log(item[key], '====item[key]====')
        })
        arr.push(obj)
      })
      // console.log(arr, '===arr====')
      await importEmployee(arr)
      // console.log(res, '====res====')
      this.$message.success('导入成功')
      this.$router.back()
    },
    // 转换日期格式
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
